package cn.bugstack.middleware.dynamic.thread.pool.trigger;

import cn.bugstack.middleware.dynamic.thread.pool.sdk.domain.model.entity.ThreadPoolAlarmEntity;
import cn.bugstack.middleware.dynamic.thread.pool.sdk.domain.model.valobj.RegistryEnumVO;
import cn.bugstack.middleware.dynamic.thread.pool.types.Response;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@Slf4j
@RestController()
@CrossOrigin("*")
@RequestMapping("/api/v1/dynamic/thread/pool/alarm")
public class ThreadPoolAlarmController {

    @Resource
    public RedissonClient redissonClient;

    /**
     * 查询线程池告警配置
     * curl --request GET \
     * --url 'http://localhost:8089/api/v1/dynamic/thread/pool/alarm/query_alarm_config?
     * appName=dynamic-thread-pool-test-app&threadPoolName=threadPoolExecutor01'
     */
    @RequestMapping(value = "query_alarm_config", method = RequestMethod.GET)
    public Response<ThreadPoolAlarmEntity> queryAlarmConfig(@RequestParam String appName, @RequestParam String threadPoolName) {
        try {
            String cacheKey = RegistryEnumVO.THREAD_POOL_ALARM_CONFIG_KEY.getKey() + "_" + appName + "_" + threadPoolName;
            ThreadPoolAlarmEntity alarmEntity = redissonClient.<ThreadPoolAlarmEntity>getBucket(cacheKey).get();
            
            // 如果没有配置，返回默认配置
            if (alarmEntity == null) {
                alarmEntity = new ThreadPoolAlarmEntity(appName, threadPoolName);
                alarmEntity.setAlarmEnabled(false);
            }
            
            return Response.<ThreadPoolAlarmEntity>builder()
                    .code(Response.Code.SUCCESS.getCode())
                    .info(Response.Code.SUCCESS.getInfo())
                    .data(alarmEntity)
                    .build();
        } catch (Exception e) {
            log.error("查询线程池告警配置异常", e);
            return Response.<ThreadPoolAlarmEntity>builder()
                    .code(Response.Code.UN_ERROR.getCode())
                    .info(Response.Code.UN_ERROR.getInfo())
                    .build();
        }
    }

    /**
     * 更新线程池告警配置
     * curl --request POST \
     * --url http://localhost:8089/api/v1/dynamic/thread/pool/alarm/update_alarm_config \
     * --header 'content-type: application/json' \
     * --data '{
     * "appName":"dynamic-thread-pool-test-app",
     * "threadPoolName": "threadPoolExecutor01",
     * "alarmEnabled": true,
     * "activeCountThreshold": 5,
     * "queueCapacityThreshold": 80,
     * "notifyType": "log",
     * "receivers": "admin"
     * }'
     */
    @RequestMapping(value = "update_alarm_config", method = RequestMethod.POST)
    public Response<Boolean> updateAlarmConfig(@RequestBody ThreadPoolAlarmEntity request) {
        try {
            log.info("更新线程池告警配置开始 {} {} {}", 
                    request.getAppName(), request.getThreadPoolName(), JSON.toJSONString(request));
            
            String cacheKey = RegistryEnumVO.THREAD_POOL_ALARM_CONFIG_KEY.getKey() + "_" + request.getAppName() + "_" + request.getThreadPoolName();
            RBucket<ThreadPoolAlarmEntity> bucket = redissonClient.getBucket(cacheKey);
            bucket.set(request);
            
            log.info("更新线程池告警配置完成 {} {}", request.getAppName(), request.getThreadPoolName());
            return Response.<Boolean>builder()
                    .code(Response.Code.SUCCESS.getCode())
                    .info(Response.Code.SUCCESS.getInfo())
                    .data(true)
                    .build();
        } catch (Exception e) {
            log.error("更新线程池告警配置异常 {}", JSON.toJSONString(request), e);
            return Response.<Boolean>builder()
                    .code(Response.Code.UN_ERROR.getCode())
                    .info(Response.Code.UN_ERROR.getInfo())
                    .data(false)
                    .build();
        }
    }
}